import React, { Component } from 'react';
import Navigation from './Navigation';
// import { Avatar } from 'antd';
import { getData, getQueryVariable, getData2 } from "../js/fetch";
import Alert from './alert_dialog_wrapper';
import '../scss/Header.scss';
// import IC0102 from '../images/IC0102.png';
// import IC0101 from '../images/教育局管理员.png';

class Header extends Component {
    constructor(props) {
        super(props);
        console.log("传入参数:", props)
        this.state = {
            UserName: "",
            PhotoPath: "",
            data: {},
            isOpen: false,
            ProductName: '校园公告信息管理',
            identity: {},
            eduIdPath: ''
        }
    }
    componentDidMount() {
        if (getQueryVariable('sysID') && window.location.href.split('?')[0].indexOf('#/RecNoticeContent') > -1) {
            return
        }
        let token = '';
        if (!sessionStorage.getItem('token')) {
            token = getQueryVariable('lg_tk');
            sessionStorage.setItem('token', token);
        } else {
            token = sessionStorage.getItem('token');
        }
        if(getQueryVariable('lg_ic')){
            let identityCode = getQueryVariable('lg_ic');
            sessionStorage.setItem("identityCode", identityCode);
            let baseUrl = sessionStorage.getItem('MainServerAddr');

            if(getQueryVariable('edu')){
                getData2(baseUrl + '/BaseApi/Global/GetUserBaseIdentityImg',{
                    appid: 400,
                    access_token: '8c5020fd261df972c2e97b6832408d81',
                    login_token: token
                }).then(res=>res.json()).then(result=>{
                    if(result.Statuscode == 200&&result.ErrCode === 0){
                        this.setState({
                            eduIdPath: result.Data
                        })
                    }
                })
            }else{
                getData2(baseUrl + "/UserMgr/PowerMgr/GetIdentityTypeByCode", {
                    SchoolID: sessionStorage.getItem("SchoolID"),
                    IdentityCodes: identityCode
                })
                .then((res)=>{
                    return res.json();
                })
                .then((result)=>{
                    if(result.Statuscode == 200 && result.Data && result.Data[0]){
                        this.setState({
                            identity: result.Data[0]
                        })
                    }
                })
            }
            
        }
        this.setState({
            UserName: decodeURIComponent(sessionStorage.getItem('UserName')),
            PhotoPath: decodeURIComponent(sessionStorage.getItem('PhotoPath')),
            ProductName: sessionStorage.getItem('ProductName'),
        }, () => {
            // sessionStorage.setItem('PsnMgrToken', sessionStorage.getItem('token'));
            let UEditorLooding = setInterval(() => {
                if (sessionStorage.getItem('PsnMgrLooding') === 1) {
                    let PsnMgrLgAssistantAddr = sessionStorage.getItem('PsnMgrLgAssistantAddr');
                    this.loadScriptOrCss([PsnMgrLgAssistantAddr + "/PsnMgr/LgAssistant/css/lancoo.cp.assistantInfoCenter.css",
                    PsnMgrLgAssistantAddr + "/PsnMgr/LgAssistant/assets/jquery.pagination.js",
                    PsnMgrLgAssistantAddr + "/PsnMgr/LgAssistant/js/lancoo.cp.assistantInfoCenter.js",
                    ]);
                    clearInterval(UEditorLooding);
                }
                // if (sessionStorage.getItem('PsnMgrLooding') === 2) {
                    // let PsnMgrLgAssistantAddr = sessionStorage.getItem('PsnMgrLgAssistantAddr');
                    // this.loadScriptOrCss([PsnMgrLgAssistantAddr + "/PsnMgr/LgAssistant/css/lancoo.cp.assistantInfoCenter.css",
                    // PsnMgrLgAssistantAddr + '/PsnMgr/LgAssistant/js/jquery-1.7.2.min.js',
                    // PsnMgrLgAssistantAddr + "/PsnMgr/LgAssistant/assets/jquery.pagination.js",
                    // PsnMgrLgAssistantAddr + "/PsnMgr/LgAssistant/js/lancoo.cp.assistantInfoCenter.js",
                    // ]);
                    // clearInterval(UEditorLooding);
                // }
            }, 500);
        })

        setInterval(() => {
            getData('publicinfo/TokenCheck', {
                unloading: true
            }).then(data => {
                return data.json()
            }).then(json => {
                if (!json.data.result) {
                    let url = window.location.href;
                    url = url.split('?');
                    if (url.length > 1 && url[1].indexOf('&') > -1) {
                        let pram = url[1].split('&');
                        url = url[0] + '?';
                        pram.forEach((item) => {
                            if (item.indexOf('lg_tk=') === -1) {
                                url += item + '&';
                            }
                        })
                        url.slice(0, url.length - 1);
                    } else {
                        url = url[0];
                    }
                    if (url.slice(-2) === '#/') {
                        url = url.slice(0, -2);
                    }
                    url = encodeURIComponent(url);
                    sessionStorage.removeItem('token');
                    // alert(  this.state.data.MainServerAddr +'/UserMgr/Login/Login.aspx?lg_sysid='+this.state.data.SysID+'&lg_preurl='+url)\
                    window.open(sessionStorage.getItem('MainServerAddr') + '/UserMgr/Login/Login.aspx?lg_sysid=' + sessionStorage.getItem('SysID') + '&lg_preurl=' + url, '_self');

                }
            })
        }, 120000)
        // getData('publicinfo/GetUserInfo', {
        //     lg_tk: sessionStorage.getItem('token')
        // }).then(data => {
        //     return data.json()
        // }).then(json => {
        //     if (json.error === '0') {
        //         let { data } = json;
        //         sessionStorage.setItem('UserID', data.UserID);
        //         sessionStorage.setItem('UserName', data.UserName);
        //         sessionStorage.setItem('UserType', data.UserType);
        //         sessionStorage.setItem('PhotoPath', data.PhotoPath);
        //         this.setState({
        //             UserName: decodeURIComponent(data.UserName),
        //             PhotoPath: decodeURIComponent(data.PhotoPath),
        //             data: data,
        //         })

        //     }
        // })
    }
    changeIsOpen() {
        this.setState({
            isOpen: true
        })
    }
    loadScriptOrCss(urlArr, num) {
        let $this = this;
        if (!num) {
            num = 0;
        }
        //正则判断是否是css;
        var reg = RegExp(/.css/);
        var scriptOrCss;

        if (reg.test(urlArr[num])) {
            // 动态生成css
            scriptOrCss = document.createElement('link');
            scriptOrCss.type = 'text/css';
            scriptOrCss.async = 'async';
            scriptOrCss.href = urlArr[num];
            scriptOrCss.rel = "stylesheet";
            document.getElementsByTagName("head")[0].appendChild(scriptOrCss);

        } else {
            // 动态生成js
            scriptOrCss = document.createElement('script');
            scriptOrCss.type = 'text/javascript';
            scriptOrCss.async = 'async';
            scriptOrCss.src = urlArr[num];
            document.body.appendChild(scriptOrCss);
        }
        if (scriptOrCss.readyState) {
            //IE下
            scriptOrCss.onreadystatechange = function () {
                if (scriptOrCss.readyState === 'complete' || scriptOrCss.readyState === 'loaded') {
                    scriptOrCss.onreadystatechange = null;
                    num++;
                    if (num === urlArr.length) {
                        return;
                    } else {
                        $this.loadScriptOrCss(urlArr, num);
                    }
                }
            }
        } else {
            //其他浏览器
            scriptOrCss.onload = function () {
                num++;
                if (num === urlArr.length) {
                    return;
                } else {
                    $this.loadScriptOrCss(urlArr, num);
                }
            }
        }
    }
    Logout(data) {
        if (data === 'true') {
            getData('publicinfo/Logout', {
            }).then(data => {
                return data.json()
            }).then(json => {
                if (json.error === '0') {
                    let url = window.location.href;
                    url = url.split('?');
                    if (url.length > 1 && url[1].indexOf('&') > -1) {
                        let pram = url[1].split('&');
                        url = url[0] + '?';
                        pram.forEach((item) => {
                            if (item.indexOf('lg_tk=') === -1) {
                                url += item + '&';
                            }
                        })
                        url.slice(0, url.length - 1);
                    } else {
                        url = url[0];
                    }
                    if (url.slice(-2) === '#/') {
                        url = url.slice(0, -2);
                    }
                    console.log(url);
                    url = encodeURIComponent(url);
                    sessionStorage.removeItem('token');
                    // alert(  this.state.data.MainServerAddr +'/UserMgr/Login/Login.aspx?lg_sysid='+this.state.data.SysID+'&lg_preurl='+url)\
                    window.open(sessionStorage.getItem('MainServerAddr') + '/UserMgr/Login/Login.aspx', '_self');
                }
            })
        }
        this.setState({
            isOpen: false
        })
    }
    openIndex() {
        var edu = getQueryVariable('edu')
        var UserType = sessionStorage.getItem('UserType')
        var UserClass = sessionStorage.getItem('UserClass')
        var token = sessionStorage.getItem('token')
        if(edu){
            if(UserType === 6 && UserClass === 2){
                window.open(sessionStorage.getItem('MainServerAddr')+'/Index_A_aspx?lg_tk='+token, '_blank');
            }
        }else{
            window.open(sessionStorage.getItem('MainServerAddr'), '_self');
        }
    }
    gotoPersonalMgr() {
        var edu = getQueryVariable('edu')
        var token = sessionStorage.getItem('token')
        if(edu){
            window.open(sessionStorage.getItem('MainServerAddr') + '/UserMgr/PersonalMgr/Default.aspx?lg_tk='+token, '_blank');
        }else{
            window.open(sessionStorage.getItem('MainServerAddr') + '/html/personalMgr/', '_blank');
        }
    }
    render() {
        let className1 = '';
        let name = '';
        let Engname = '';
        let LitleName = '';
        
        let {
            identity,
            eduIdPath
        } = this.state;
        switch(this.props.headerStyle){
            case 1:
                className1 = 'notice-header-logn  noticeHeader';
                name = '通知公告';
                Engname = 'Announcements';
                break;
            case 2:
                className1 = 'notice-header-logn  QueHeader';
                name = '问卷调查';
                Engname = 'Questionnaire Survey';
                break;
            case 3:
                className1 = ' notice-header-logn notice-header-logn1  newsHeader';
                name = '新闻资讯';
                Engname = 'News and Information';
                break;
            case 4:
                className1 = ' notice-header-logn notice-header-logn1  newsHeader';
                name = '意见反馈';
                Engname = 'Feedback';
                break;
            case 11:
                className1 = 'notice-header-logn  noticeHeader';
                name = '通知公告';
                LitleName = '- 模板库';
                Engname = 'Announcements - Template Library';
                break;
            default:
                    className1 = 'notice-header-logn  noticeHeader';
                    name = 'name';
                    LitleName = 'name';
                    Engname = 'EngName';
        }
        var edu = getQueryVariable('edu')
        // var UserType = sessionStorage.getItem('UserType')
        // var UserClass= sessionStorage.getItem('UserClass')
        // const { HeaderSetting,LoginUser,HeaderMenuToggle,LogOut } = this.props;

        // const { TopVisit,OnlineUsers,SuspiciousLogin,OnlineDiskUsed,GroupFileSpaceUsed } = HeaderSetting;

        // let onlineNum = OnlineDiskUsed?parseInt(OnlineDiskUsed.split('/')[0]):0;

        // let onlineDiskInfo = this.diskSize(onlineNum);

        // let groupNum = GroupFileSpaceUsed?parseInt(GroupFileSpaceUsed.split('/')[0]):0;

        // let groupInfo = this.diskSize(groupNum);
        // console.log(this.state)
        // console.log(identity,'identity')

        // console.log(edu,'edu')
        return (
            <div className="notice-header">
                <div className="notice-header-top">
                    <div className="box-middle">
                        <span className='login_logo'></span>
                        <span onClick={() => { this.openIndex() }}>{this.state.ProductName}</span>
                        <div className="notice-header-right">
                            <div id="Assistant_infoCenter" ></div>
                            {
                                edu?null:<div className='notice-header-border' ></div>
                            }
                            <div className='notice-header-sculpture' style={{ 'backgroundImage': `url(${this.state.PhotoPath})` }} onClick={() => { this.gotoPersonalMgr() }}></div>
                            <div className='notice-header-name' onClick={() => { this.gotoPersonalMgr() }} >{this.state.UserName}</div>
                            {
                                edu?
                                ( <img src={eduIdPath} alt=""/> )
                                :(
                                    identity.IsPreset?
                                    identity.IconUrl? 
                                    <img src={identity.IconUrl} style={{
                                        margin: '0 4px'
                                    }} alt=""/>:
                                    <div className="iconUrl-container">
                                        <img src={identity.IconUrl} alt=""/>
                                        {identity.IdentityName}
                                    </div>:
                                    ""
                                )
                                
                            }
                            
                            <i onClick={() => { this.changeIsOpen() }}></i>
                        </div>
                        <div >
                            <span className={className1}  ></span>
                            <span className="notice-header-title" style={{left: (this.props.headerStyle === 2? '88px': '')}}>{this.props.headerName ? this.props.headerName : name}</span> <span className='header-litle'>{LitleName}</span>
                            <span className="notice-header-title1" style={{left: (this.props.headerStyle === 2? '88px': '')}}>{Engname}</span>
                            <span id="circle-title" style={{
                                display: (this.props.type === "circle"? "block": "none")
                            }}>{this.props.circleText}</span>
                        </div>
                    </div>
                    <ul className='frame-triangle-wrapper'>
                        <li></li>
                        <li></li>
                        <li></li>
                        <li></li>
                        <li></li>
                        <li></li>
                        <li></li>
                        <li></li>
                        <li></li>
                        <li></li>
                    </ul>
                    <Alert message='您确定要退出登录么?' isOpen={this.state.isOpen} chooseFn={(data) => { this.Logout(data) }}></Alert>
                    <Navigation />
                </div>
            </div>
        )

    }

}

export default Header;